//
//  LogoScene.cpp
//  client
//
//  Created by sunpeng on 8/14/15.
//
//

#include "LogoScene.h"
#include "ui/CocosGUI.h"
#include "AudioEngine.h"
#include "Localization.h"
#include "AppDelegate.h"

// #include <ctime>

#include "InstallScene.h"

#ifdef USE_PWRD
#include "Pwrd/PwrdSdkApi.hpp"
#endif

USING_NS_CC;
//using namespace CocosDenshion;
using namespace cocos2d::experimental;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
using namespace cocos2d::experimental::ui;
#endif

static int _audioId = AudioEngine::INVALID_AUDIO_ID;

Scene* LogoScene::createScene(bool withCG)
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();
    
    // 'layer' is an autorelease object
    auto layer = LogoScene::create();
    layer->setWithCG(withCG);
    layer->setKeyboardEnabled(true);
    
    // add layer as a child to scene
    scene->addChild(layer);
    
    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool LogoScene::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    interrupted = true;
    
    beginTime = time(nullptr);
    
    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();
    
    auto dispatcher=Director::getInstance()->getEventDispatcher();
    auto touchListener=EventListenerTouchOneByOne::create();
    touchListener->onTouchBegan =CC_CALLBACK_2(LogoScene::actionInterrupted,this);
    dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
	dispatcher->setEnabled(true);
    

    
    // add "Logo" splash screen"

    CSLoader::getInstance()->setAutoPlayAni(true);
    CSLoader::getInstance()->setAnimationIsLoop(false);
    logo=CSLoader::createNode("ui2/Loading.csb");
    logo->setContentSize(Size(visibleSize.width,visibleSize.height));
    
    this->addChild(logo);
    cocos2d::ui::Helper::doLayout(logo);
    
    logoAction = static_cast<cocostudio::timeline::ActionTimeline*>(logo->getActionByTag(0));
    logoAction->setLastFrameCallFunc(CC_CALLBACK_0(LogoScene::actionEnd, this));
    return true;
}

void LogoScene::setWithCG(bool withCG)
{
    this->withCG = withCG;
}

void LogoScene::onEnterTransitionDidFinish()
{
    cocos2d::log("AppStartTime: LogoScene Enter");
    Layer::onEnterTransitionDidFinish();

    // clock_t now = clock();
    AppDelegate::delayInit();
    // cocos2d::log("AppStartTime logo.delayInit = %f", (clock()-now)/1000.0);
}

bool LogoScene::actionInterrupted(Touch *touch,Event *event)
{
    double duration = difftime(time(nullptr), beginTime);
    if(duration < 2.0){
        return false;
    }
    
    cocos2d::log("LogoScene actionInterrupted\n");
    if (!interrupted) {
        interrupted=true;
        this->afterLogo();
    }

    return false;
}

void LogoScene::actionEnd()
{
    logoAction->clearLastFrameCallFunc();
    cocos2d::log("logo end\n");

    cocos2d::log("===>LogoScene withCG :%d", withCG?1:0);

    interrupted = false;
    if(withCG){
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
        Size visibleSize = Director::getInstance()->getVisibleSize();
        Vec2 origin = Director::getInstance()->getVisibleOrigin();
        
        // play logo video if file exist
        FileUtils* fileUtils = FileUtils::getInstance();
        std::string path = fileUtils->fullPathForFilename("res/video/video_01_opening.mp4");
        bool isExist = fileUtils->isFileExist(path);
        if (isExist){
            cocos2d::log("LogoScene VideoPlayer path= %s \n", path.c_str());
            auto pos = Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height /2);
            auto videoPlayer = VideoPlayer::create();
            videoPlayer->setPosition(pos);
            videoPlayer->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
            videoPlayer->setContentSize(visibleSize);
            this->addChild(videoPlayer);
            
            videoPlayer->addEventListener([this](Ref* sender, VideoPlayer::EventType eventType){
                switch (eventType) {
                    case VideoPlayer::EventType::PLAYING:
                        cocos2d::log("LogoScene VideoPlayer PLAYING\n");
                        break;
                    case VideoPlayer::EventType::PAUSED:
                        cocos2d::log("LogoScene VideoPlayer PAUSED\n");
                        break;
                    case VideoPlayer::EventType::STOPPED:
                        cocos2d::log("LogoScene VideoPlayer STOPPED\n");
                        if(!interrupted){
                            interrupted = true;
                            this->afterLogo();
                        }
                        PwrdSdkApi::wanmeiTrackEvent("gameSkipCG");
                        break;
                    case VideoPlayer::EventType::COMPLETED:
                        cocos2d::log("LogoScene VideoPlayer COMPLETED\n");
                        if(!interrupted){
                            interrupted = true;
                            this->afterLogo();
                        }
                        PwrdSdkApi::wanmeiTrackEvent("gameEndCG");
                        break;
                    default:
                        break;
                }
            });
            
            videoPlayer->setKeepAspectRatioEnabled(true);
            videoPlayer->setFullScreenEnabled(true);
            
            videoPlayer->setFileName(path);
            videoPlayer->play();
            PwrdSdkApi::wanmeiTrackEvent("gameBeginCG");
        }else{
            this->afterLogo();
        }
#else
        this->afterLogo();
#endif
    }else{
        this->afterLogo();
    }
}

void LogoScene::afterLogo()
{
    if(_audioId!=AudioEngine::INVALID_AUDIO_ID){
        AudioEngine::stop(_audioId);
        _audioId=AudioEngine::INVALID_AUDIO_ID;
    }
    
    if(!UserDefault::getInstance()->getBoolForKey("AM.isMuteMusic",false)){
        _audioId = AudioEngine::play2d("music/login.mp3",true);
        float volume = UserDefault::getInstance()->getFloatForKey("AM.MusicVolumeMax",1.0f);
        AudioEngine::setVolume(_audioId, volume);
    }
    
    auto scene=TransitionFade::create(1.0f, createInstallScene(),Color3B::BLACK);
    
    Director::getInstance()->replaceScene(scene);
}

void LogoScene::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
    Layer::onKeyPressed(keyCode, event);
    
    if (keyCode == EventKeyboard::KeyCode::KEY_BACK)
    {
        cocos2d::log("===>LogoScene   menuCloseCallback ");
        AppDelegate::closeApp();
    }
}
